function handles = traceAveraging(handles)
% traceAveraging
%
% This makes a stack of traces from each map, and averages them.
%
% Editing:
% gs june 2005 -- started
% gs july 2005 -- continued
% -------------------------------------------

% load 
for m = 1 : handles.data.analysis.numberOfMaps
    eval(['traceArray(:,:,m) = handles.data.map.map' num2str(m) '.bsArray;']);
    eval(['mapPattern(:,:,m) = handles.data.map.map' num2str(m) '.mapPattern;']);
end

% sort by array order, not map order
for m = 1 : handles.data.analysis.numberOfMaps
    traces = traceArray(:,:,m)';
    pattern = mapPattern(:,:,m);
    mapPatVec = reshape(pattern, numel(pattern), 1);
    mapIndVec = (1:numel(mapPatVec))';
    arrayPatternAndInds = [mapPatVec mapIndVec];
    scrambledPatternAndInds = sortrows(arrayPatternAndInds, 1);
    sortOrder = scrambledPatternAndInds(:,2);
    sortedData = sortrows([sortOrder traces]);
    sortedData(:,1) = [];
    sortedTraceArray(:, :, m) = sortedData';
end

% average
handles.data.map.traceAvg.bsArray = []; % reset
handles.data.map.traceAvg.bsArray = mean(sortedTraceArray, 3);

[r,c] = size(pattern);
handles.data.map.traceAvg.patternSize = [r c];